import { _decorator, Button, Color, Component, director, DynamicAtlasManager, Label, Node, Prefab, Slider, Sprite, SpriteFrame, Toggle, tween, v3 } from 'cc';
import { AudioManager, Core } from './Core/Core';
import { EEvent, EGameMode, EGameSystem, EPet, EPlayerType, EScene } from './Config/Enum';
import { Context } from './Context';
import { PlayerConfig } from './Config/PlayerConfig';
import { ResourceManager } from './Core/ResourceManager';
import { PicPath, sceneRes } from './Config/ResourceConfig';
import { Instruction } from './UI/Instruction';
import { Util } from './Util';
import { SystemUnlockMap } from './Config/Config';

const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {

    selectedPlayers: Set<EPlayerType> = new Set();
    currentPlayer: EPlayerType;

    ndMap: Node;
    // Header Nodes
    ndJunling: Node;
    ndMoney: Node;
    ndPeople: Node;
    ndFood: Node;
    ndWoodRock: Node;
    ndWeather: Node;
    
    Label_Money: Label;
    Label_Renown: Label;
    Label_Stage: Label;
    Label_Junling: Label;
    Label_People: Label;
    Label_Food: Label;
    Label_WoodRock: Label;
    // 添加一个 Label 引用，用于更新时间文本
    lbTime: Label | null = null;
    
    stage_normal: number = 1;
    renown: number = 0;

    // FOOTER按钮节点
    ndBtnPlayer: Node;
    ndBtnBattle: Node;

    // MAP按钮节点
    ndBtnGeneral: Node;
    ndBtnPet: Node;
    ndBtnWall: Node;
    ndBtnShop: Node;
    ndBtnForge: Node;
    ndBtnBag: Node;
    ndBtnTreasure: Node;
    ndBtnBeaconTower: Node;


    //ndBtnMartial: Node;

    // 帮助和设置节点
    ndBtnHandbok: Node;
    ndBtnSetting: Node;

    // 面板节点 (Views)
    spBg: Sprite;

    ndGeneralView: Node;
    ndPetView: Node;
    ndWallView: Node;
    ndShopView: Node;
    ndForgeView: Node;
    ndBagView: Node;
    ndTreasureView: Node;
    ndBeaconTowerView: Node;

    ndPlayerView: Node;
    ndBattleView: Node;
    ndCultivationBoard: Node;
    ndArsenalView: Node;
    ndMartialView: Node;

    ndSignView: Node;

    ndHandbookView: Node;
    ndSettingView: Node;
    ndUnlockPlayerView: Node;
    ndTIme: Node;
    // 其他
    ndTips_UnlockSkill: Node;
    ndInstruction: Node;

    // 面板集合
    private _allMainPanels: Node[] = [];

    onLoad(): void {
        console.log("Main onLoad");      
        AudioManager.Instance.playMusic("start_bgm");

        // 【修改点】移除了 Main 里的定时器，改为 Core 统一管理
        
        Core.Instance.startBackgroundPreload_assetList(Core.Instance.getAllEnemyFileList());

        Context.ndTips = this.node.getChildByName("Tips");

        if(Core.Instance.junlingGot > 0){
            Core.Instance.showItemGot({name: "军令", count: Core.Instance.junlingGot});
            Core.Instance.junlingGot = 0; 
            Core.Instance.save();
        }

        // --- 节点绑定 ---
        this.ndMap = this.node.getChildByName("Map");

        this.ndBtnPet = this.ndMap.getChildByName("Button_Pet");
        this.ndBtnWall = this.ndMap.getChildByName("Button_Wall");
        this.ndBtnShop = this.ndMap.getChildByName("Button_Shop");
        this.ndBtnForge = this.ndMap.getChildByName("Button_Forge");
        this.ndBtnGeneral = this.node.getChildByName("Button_General");
        this.ndBtnBag = this.node.getChildByName("Button_Bag");
        this.ndBtnTreasure = this.node.getChildByName("Button_Treasure");
        this.ndBtnBeaconTower = this.node.getChildByName("Button_BeaconTower");

        this.ndPetView = this.node.getChildByName("PetView");
        this.ndWallView = this.node.getChildByName("WallView");
        this.ndShopView = this.node.getChildByName("ShopView");
        this.ndForgeView = this.node.getChildByName("ForgeView");
        this.ndGeneralView = this.node.getChildByName("GeneralView");
        this.ndBagView = this.node.getChildByName("BagView");
        this.ndTreasureView = this.node.getChildByName("TreasureView");
        this.ndBeaconTowerView = this.node.getChildByName("BeaconTowerView");









        this.ndPlayerView = this.node.getChildByName("PlayerView");
        this.ndArsenalView = this.node.getChildByName("ArsenalView");
        this.ndBattleView = this.node.getChildByName("BattleView");
        //this.ndMartialView = this.node.getChildByName("MartialView");
        this.ndSignView = this.node.getChildByName("SignView");
        this.ndHandbookView = this.node.getChildByName("HandbookView");
        this.ndSettingView = this.node.getChildByName("SettingView");
        this.ndCultivationBoard = this.node.getChildByName("CultivationBoard");

        this._allMainPanels = [
            this.ndPlayerView, this.ndBattleView, 
            this.ndGeneralView, this.ndBagView, this.ndPetView, this.ndWallView, this.ndShopView, this.ndForgeView, this.ndTreasureView,this.ndBeaconTowerView,
            this.ndSignView, this.ndHandbookView,this.ndSettingView, 
        ];

        Context.ndEquipmentSwitchView = this.node.getChildByName("EquipmentSwitchView");
        Context.ndArsenalView = this.node.getChildByName("ArsenalView");
        Context.ndPlayerView = this.ndPlayerView;

        const ndFooter = this.node.getChildByName("Footer");
        //this.ndBtnMartial = ndFooter.getChildByName("Button_Martial");
        this.ndBtnGeneral = ndFooter.getChildByName("Button_General");
        this.ndBtnBag = ndFooter.getChildByName("Button_Bag");
        this.ndBtnPet = ndFooter.getChildByName("Button_Pet");

        const ndHeader = this.node.getChildByName("Header");
        this.ndJunling = ndHeader.getChildByName("Junling");
        this.ndMoney = ndHeader.getChildByName("Money");
        this.ndPeople = ndHeader.getChildByName("People");
        this.ndFood = ndHeader.getChildByName("Food");
        this.ndWoodRock = ndHeader.getChildByName("WoodRock");
        this.ndWeather = ndHeader.getChildByName("Weather");
        this.ndTIme = ndHeader.getChildByName("Time");

        this.Label_Junling = this.ndJunling.getChildByName("Value").getComponent(Label);
        this.Label_Money = this.ndMoney.getChildByName("Value").getComponent(Label);
        this.Label_People = this.ndPeople.getChildByName("Value").getComponent(Label);
        this.Label_Food = this.ndFood.getChildByName("Value").getComponent(Label);
        this.Label_WoodRock = this.ndWoodRock.getChildByName("Value").getComponent(Label);

        this.spBg = this.ndMap.getComponent(Sprite);
        this.ndTips_UnlockSkill = this.node.getChildByName("Tips_UnlockSkill");
        this.ndUnlockPlayerView = this.node.getChildByName("UnlockPLayerView");
        this.ndInstruction = this.node.getChildByName("Instruction");
    }

    protected onEnable(): void {
        this.ndJunling.on(Node.EventType.TOUCH_END, this.onOpenInstruction_Junling, this);
        this.ndMoney.on(Node.EventType.TOUCH_END, this.onOpenInstruction_Money, this);
        this.ndPeople.on(Node.EventType.TOUCH_END, this.onOpenInstruction_People, this);
        this.ndFood.on(Node.EventType.TOUCH_END, this.onOpenInstruction_Food, this);
        this.ndWoodRock.on(Node.EventType.TOUCH_END, this.onOpenInstruction_WoodRock, this);

        // 监听资源变化事件，这是 UI 更新的关键
        Core.Instance.event.on(EEvent.ResourceChanged, this.onResourceChanged, this);

        const sliderNode = this.ndSettingView.getChildByName("Board").getChildByName("Music").getChildByName("Slider");
        if(sliderNode) {
            sliderNode.getComponent(Slider).progress = Core.Instance.volume;
        }
    }

    protected onDisable(): void {
        this.ndJunling.off(Node.EventType.TOUCH_END, this.onOpenInstruction_Junling, this);
        this.ndMoney.off(Node.EventType.TOUCH_END, this.onOpenInstruction_Money, this);
        this.ndPeople.off(Node.EventType.TOUCH_END, this.onOpenInstruction_People, this);
        this.ndFood.off(Node.EventType.TOUCH_END, this.onOpenInstruction_Food, this);
        this.ndWoodRock.off(Node.EventType.TOUCH_END, this.onOpenInstruction_WoodRock, this);

        Core.Instance.event.off(EEvent.ResourceChanged, this.onResourceChanged, this);
    }

    start() {
        this.stage_normal = Core.Instance.modeMaxStage[EGameMode.Normal] || 1; 

        // 获取时间 Label 组件
        if (this.ndTIme) {
            this.lbTime = this.ndTIme.getComponent(Label) || this.ndTIme.getComponentInChildren(Label);
        }


        this.loadHeader();
        // [修改] 立即执行一次环境更新
        this.updateEnvironment();
        // [修改] 每分钟更新一次环境（没必要每帧 update，太费性能）
        this.schedule(this.updateEnvironment, 60);

        this.scheduleOnce(() => {
            // 先检测是否有新解锁（如果有，会弹窗）
            Core.Instance.checkNewSystemUnlock();
            this.checkUnlockSystem(); 
            this.checkUnlockPlayer(); 
            this.checkUnlockMode();   
        }, 0.2);

        // Core.Instance.showUnlockPop(
        //     "功能解锁", 
        //     "已开启 [宠物系统]\n快去培养你的伙伴吧！", 
        //     "pic/other/fox", // 传入你的图标路径
        //     () => {
        //         console.log("弹窗关闭了，引导玩家去点击宠物按钮");
        //         // 这里可以接新手引导
        //     }
        // );
    }

    onDestroy() {
        // Main 销毁时不需要清理资源定时器，因为它在 Core 中
    }

    

    private togglePanel(targetPanel: Node) {
        if (!targetPanel) return;
        const isCurrentlyActive = targetPanel.active;
        this._allMainPanels.forEach(panel => {
            if (panel && panel.isValid) panel.active = false;
        });
        targetPanel.active = !isCurrentlyActive;
    }

    updateBackgroundOpacity() {
        const now = new Date();
        const totalMinutes = now.getHours() * 60 + now.getMinutes();
        let opacity = 1;
        
        if (totalMinutes >= 360 && totalMinutes < 480) {
            opacity = 0.7 + 0.3 * (totalMinutes - 360) / 120;
        } else if (totalMinutes >= 480 && totalMinutes < 960) {
            opacity = 1;
        } else if (totalMinutes >= 960 && totalMinutes < 1200) {
            opacity = 1 - 0.5 * (totalMinutes - 960) / 240;
        } else {
            opacity = 0.5;
        }
        
        if(this.spBg && this.spBg.isValid) {
            const color = this.spBg.color;
            this.spBg.color = new Color(color.r, color.g, color.b, opacity * 255);
        }
    }

/**
     * [功能 1 & 2 & 3] 统一的环境更新逻辑
     * 更新时间显示、背景亮度
     */
    updateEnvironment() {
        const now = new Date();
        const hour = now.getHours();
        // const minutes = now.getMinutes(); // 如果需要更精确的光照渐变可以用分钟

        // --- 1. 更新时间文本 ---
        if (this.lbTime) {
            const shichen = Util.getShichen(hour);
            const shichenDesc = Util.getShichenDesc(hour); // 可选
            // 格式：公元1267年 南宋 襄阳城 [子时-夜半]
            // 结合 Core.ts 里的 day 属性，显示游戏里的天数
            this.lbTime.string = `公元1267年,南宋,襄阳城,${shichen} \n已坚守 ${Core.Instance.day} 天`;
        }

        // --- 2. 更新背景亮度 (沉浸感) ---
        this.updateBackgroundOpacityByTime(hour);
    }

    /**
     * 根据小时调整背景亮度
     * 0点最暗，12点最亮
     */
    updateBackgroundOpacityByTime(hour: number) {
        // 1. 安全检查
        if (!this.spBg || !this.spBg.isValid) return;

        let colorVal = 255; // 默认最亮 (255, 255, 255)
        
        // 2. 简单的光照逻辑 (RGB越低越暗)
        if (hour >= 6 && hour < 17) {
            // [白天] 全亮
            colorVal = 255; 
        } else if (hour >= 17 && hour < 19) {
            // [黄昏] 稍微变暗
            colorVal = 200; 
        } else if (hour >= 19 || hour < 5) {
            // [夜晚] 最暗 (注意不要设为0，否则全黑看不见了)
            colorVal = 100; 
        } else if (hour >= 5 && hour < 6) {
            // [黎明] 逐渐变亮
            colorVal = 180;
        }

        const targetColor = new Color(colorVal, colorVal, colorVal, 255);

        // === 核心修改点 ===
        // 错误写法: tween(this.spBg.node) -> Node 没有 color 属性
        // 正确写法: tween(this.spBg)      -> Sprite 组件才有 color 属性
        tween(this.spBg) 
             .to(2.0, { color: targetColor }) 
             .start();
    }

    // --- 资源更新 ---
    
    // Core 中触发 EEvent.ResourceChanged 时调用
    onResourceChanged(){
        this.loadHeader();
    }

    loadHeader(){
        if(this.Label_Junling) this.Label_Junling.string = `${Core.Instance.junling}/120`;
        if(this.Label_Money) this.Label_Money.string = Core.Instance.gold.toString();
        if(this.Label_People) this.Label_People.string = Core.Instance.people.toString();
        if(this.Label_Food) this.Label_Food.string = Core.Instance.food.toString();
        if(this.Label_WoodRock) this.Label_WoodRock.string = Core.Instance.woodRock.toString();
        if(this.ndWeather && this.ndWeather.getComponent(Label)) {
            this.ndWeather.getComponent(Label).string = Core.Instance.getWeatherName();
        }
    }

    // --- 解锁与 UI ---

    // 解锁系统的关隘：
    // 3: 商店系统
    // 5: 城墙系统
    // 10: 将军系统
    // 12: 烽火台系统
    // 15: 灵兽系统
    // 20: 锻造系统
    // 25: 探宝系统
// 1. 重写 checkUnlockSystem 方法
    // 这个方法在 start() 或 onEnable() 时调用，用于刷新所有按钮的 灰色/锁头 状态
    checkUnlockSystem() {
        // 建立按钮节点与系统枚举的映射关系
        // 这样写比一堆 if-else 更清晰
        const btnMap: { [key: number]: Node } = {
            [EGameSystem.Shop]: this.ndBtnShop,
            [EGameSystem.Wall]: this.ndBtnWall,
            [EGameSystem.General]: this.ndBtnGeneral,
            [EGameSystem.Forge]: this.ndBtnForge,
            [EGameSystem.Pet]: this.ndBtnPet,
            [EGameSystem.Beacon]: this.ndBtnBeaconTower,
            [EGameSystem.Treasure]: this.ndBtnTreasure,
            // 如果以后有 Martial (修炼/功法)，加在这里:
            // [EGameSystem.Martial]: this.ndBtnMartial, 
        };

        // 遍历映射，批量更新按钮状态
        for (const systemIdStr in btnMap) {
            const systemId = Number(systemIdStr) as EGameSystem;
            const btnNode = btnMap[systemId];
            
            if (btnNode && btnNode.isValid) {
                this.updateButtonVisualState(btnNode, systemId);
            }
        }
    }

    // [新增辅助方法] 更新单个按钮的视觉状态（锁头/变灰）
    private updateButtonVisualState(btnNode: Node, system: EGameSystem) {
        // 询问 Core 是否解锁
        const isUnlocked = Core.Instance.isSystemUnlocked(system);
        
        const icon = btnNode.getChildByName('Icon');
        const locker = btnNode.getChildByName('Locker');
        
        if (icon) {
            // 解锁显示原色(WHITE)，未解锁显示灰色(GRAY)
            icon.getComponent(Sprite).color = isUnlocked ? Color.WHITE : Color.GRAY;
        }
        
        if (locker) {
            // 未解锁显示锁头，解锁隐藏
            locker.active = !isUnlocked;
        }
    }

    // [新增辅助方法] 点击按钮时的通用检查逻辑
    private checkSystemOpen(system: EGameSystem): boolean {
        // 1. 如果已解锁，通过
        if (Core.Instance.isSystemUnlocked(system)) {
            return true;
        } 
        
        // 2. 如果未解锁，查找配置并提示玩家
        const config = SystemUnlockMap.get(system);
        if (config) {
            // 提示：通过第 X 关解锁
            Core.Instance.showTips(`通关 [襄阳烽烟] 第 ${config.unlockStage - 1} 关后解锁`);
        } else {
            // 如果没配置但被锁了（理论上不该发生），提示默认信息
            Core.Instance.showTips("该功能暂未解锁");
        }
        return false;
    }


    checkUnlockPlayer() {
        if (Core.Instance.unlockedPlayers.length === 0 || Core.Instance.playerLockSet.size === 0) return;
        const stagesToCheck = [3, 7, 13, 19];
        for (const stage of stagesToCheck) {
            if (this.stage_normal >= stage && !Core.Instance.unlockedStages[stage]) {
                this.unlockPlayer(stage);
            }
        }
    }

    unlockPlayer(stage: number) {
        const lockSetArray = Array.from(Core.Instance.playerLockSet);
        if (lockSetArray.length === 0) return;
        
        const playerToUnlock = lockSetArray[Math.floor(Math.random() * lockSetArray.length)];
        Core.Instance.unlockedPlayers.push(playerToUnlock);
        Core.Instance.playerLockSet.delete(playerToUnlock);
        Core.Instance.unlockedStages[stage] = true;

        const playerName = PlayerConfig[playerToUnlock].name;
        this.ndUnlockPlayerView.setScale(0, 0);
        this.ndUnlockPlayerView.active = true;

        const labelNode = this.ndUnlockPlayerView.getChildByName("Label");
        const playerNode = this.ndUnlockPlayerView.getChildByName("Player");
        const lineNode = this.ndUnlockPlayerView.getChildByName("Line");

        if(labelNode) labelNode.getComponent(Label).string = `招募到新义士：${playerName}`;
        if(playerNode) {
            const path = PicPath[playerToUnlock + "IdleFront"] + "/Idle_1";
            playerNode.getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(path);
        }
        if(lineNode) lineNode.getComponent(Label).string = PlayerConfig[playerToUnlock].line1;

        tween(this.ndUnlockPlayerView)
            .to(0.5, { scale: v3(1, 1, 1) }, { easing: 'backOut' })
            .start();

        Core.Instance.save();
    }

    checkUnlockMode() {
        if(this.stage_normal >= 50) return;
        const unlockConfig = [
            { stage: 10, mode: EGameMode.Endless },
            { stage: 12, mode: EGameMode.Gold },
            { stage: 15, mode: EGameMode.Gem },
            { stage: 20, mode: EGameMode.Boss }
        ];
        for (const cfg of unlockConfig) {
            if (this.stage_normal >= cfg.stage && Core.Instance.unlockedModes.indexOf(cfg.mode) === -1) {
                this.unlockMode(cfg.mode);
            }
        }
    }

    unlockMode(mode: EGameMode) {
        if (Core.Instance.unlockedModes.indexOf(mode) === -1) {
            Core.Instance.unlockedModes.push(mode);
            console.log("解锁模式", mode);
        }
    }

    // --- UI 交互 ---
    onOpenInstruction_Junling() { this.showInstruction("军令", this.ndJunling); }
    onOpenInstruction_Money() { this.showInstruction("钱币", this.ndMoney); }
    onOpenInstruction_People() { this.showInstruction("军民", this.ndPeople); }
    onOpenInstruction_Food() { this.showInstruction("粮草", this.ndFood); }
    onOpenInstruction_WoodRock() { this.showInstruction("木石", this.ndWoodRock); }

    private showInstruction(msg: string, targetNode: Node) {
        if (this.ndInstruction) {
            this.ndInstruction.getComponent(Instruction).init(msg, targetNode.worldPosition);
            this.ndInstruction.active = true;
        }
    }


    onBtnPlayerView() { this.togglePanel(this.ndPlayerView); }

    onBtnBattleView() {
        this.togglePanel(this.ndBattleView);
        this.checkUnlockPlayer(); 
    }
    onBtnMartialView() {
        if (this.stage_normal < 5) {
            Core.Instance.showTips("通过襄阳烽烟第5关解锁");
            return;
        }
        this.togglePanel(this.ndMartialView);
    }

    onBtnSignView() { this.togglePanel(this.ndSignView); }
    onBtnCultivationBoard() { this.ndCultivationBoard.active = !this.ndCultivationBoard.active; }
    onBtnHandbook() { this.togglePanel(this.ndHandbookView); }
    onBtnSettinView() { this.togglePanel(this.ndSettingView); }
    onBtnUnlockPlayerView() { this.ndUnlockPlayerView.active = !this.ndUnlockPlayerView.active; }
    onSliderChangeMusicVolume(slider: Slider, customerEventData: string) {
        AudioManager.Instance.setMusicVolume(slider.progress);
    }

    // Map下的view
    // ndGeneralView: Node;
    // ndPetView: Node;
    // ndWallView: Node;
    // ndShopView: Node;
    // ndForgeView: Node;
    // ndBagView: Node;
    // ndBtnTreasureView: Node;
    // ndBeaconTowerView: Node;
// 将军府
    onButtonOpenGeneralView() { 
        if (this.checkSystemOpen(EGameSystem.General)) {
            this.togglePanel(this.ndGeneralView); 
        }
    }

    // 宠物
    onButtonOpenPetView() { 
        if (this.checkSystemOpen(EGameSystem.Pet)) {
            this.togglePanel(this.ndPetView); 
        }
    }

    // 城墙
    onButtonOpenWallView() {
        if (this.checkSystemOpen(EGameSystem.Wall)) {
            this.togglePanel(this.ndWallView);
        }
    }

    // 商店
    onButtonOpenShopView() {
        if (this.checkSystemOpen(EGameSystem.Shop)) {
            this.togglePanel(this.ndShopView);
        }
    }

    // 锻造
    onButtonOpenForgeView() {
        if (this.checkSystemOpen(EGameSystem.Forge)) {
            this.togglePanel(this.ndForgeView);
        }
    }

    // 探宝
    onButtonOpenTreasureView() {
        if (this.checkSystemOpen(EGameSystem.Treasure)) {
            this.togglePanel(this.ndTreasureView);
        }
    }

    // 烽火台
    onButtonOpenBeaconTowerView() {
        if (this.checkSystemOpen(EGameSystem.Beacon)) {
            this.togglePanel(this.ndBeaconTowerView);
        }
    }
    
    // 背包 (通常默认开放，不需要 checkSystemOpen，除非你也想根据关隘锁背包)
    onButtonOpenBagView() { 
        this.togglePanel(this.ndBagView); 
    }
}